package com.icangya.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.icangya.Value.StaticValue;
import com.icangya.domain.Admin;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import static com.icangya.Value.StaticValue.ADMIN_USER_SESSION;

/**
 * 登录拦截器
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    private Logger logger = Logger.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request,  HttpServletResponse response, Object handler) throws Exception {
        String requestUrl = request.getRequestURL().toString(); /** 拦截到用户的请求了 */
        logger.debug("requestUrl:" + requestUrl);
                /** 判断session是否存在用户,如果存在说明用户已经登录了,应该放行 */
        Admin user = (Admin) request.getSession().getAttribute(ADMIN_USER_SESSION);
       if (user != null) {
            this.addCurrentUser(user);
            logger.debug("requestUrl:" + requestUrl + "->被放行！");
                /** 当前请求：每个请求是否都是一个线程   */
            LoginInterceptor.addCurrentUser(user);
            return true;
        } else {
            response.sendRedirect(StaticValue.WX.BASE_URL + "/Shopping_Mall/login.html");// 重定向
                logger.debug("requestUrl:" + requestUrl + "->被拦截！");
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
       // LoginInterceptor.removeCurrentUser();
    }

    private static ThreadLocal<Admin> users = new ThreadLocal<Admin>();

    public static void addCurrentUser(Admin user) {
        if (users.get() == null) {
            users.set(user);
        }
    }

    public static Admin getCurrentUser() {
        return users.get();
    }

    public static void removeCurrentUser() {
        users.remove();
    }

}
